<template>
  <!-- 设备详情 -->
  <view class="deviceManInfo">
    <view class="wrapper-content">
      <view class="wrapper-item">
        <view class="device-name">{{ options.name }}</view>
        <view class="mnCode">
          MN码:{{ options.monitorMn || options.deviceMonitorMn }}
        </view>

        <view class="item-content">
          <view class="item-cycle" v-for="item in devList" :key="item.id">
            <view class="devicename" :data-url="`${item.devUrl}?data=${encodeURIComponent(
                JSON.stringify(options)
              )}`" @click="handleClickRouter">
              <image :src="
                  baseImgUrl +
                  (item.flag == 1 ? 'righticon.png' : 'addIcon.png')
                " mode="aspectFill"></image>
              {{ item.name }}
            </view>
          </view>
        </view>

        <view class="item-content" style="
            border-top: 1px solid #f1f1f1;
            border-bottom: 1px solid #f1f1f1;
          ">
          <view class="con-cycle">
            <view class="cycleName">清洗周期</view>
            <view class="cycleTime">{{ options.restaurant.cleanCycle }}天</view>
          </view>
          <view class="con-cycle">
            <view class="cycleName">最近一次清洗时间</view>
            <view class="cycleTime">
              {{
                options.restaurant.cleanTime
                  ? formatters(options.restaurant.cleanTime, "YY/MM/DD")
                  : "暂无"
              }}
            </view>
          </view>
          <view class="con-cycle">
            <view class="cycleName">清洗倒计时</view>
            <view class="cycleTime">
              {{ daySub(options.restaurant.expireDay) }}
            </view>
          </view>
        </view>

        <view class="dining-room">
          <view class="din-title" style="margin-bottom: 10rpx">
            <view>
              <image :src="baseImgUrl + 'house_icon.png'" mode="aspectFill"></image>
            </view>
            <view>
              {{
                options.restaurantId_dictText ||
                options.restaurant.restaurantName
              }}
            </view>
          </view>
          <view class="dinAddress">
            <text>所属街道:</text>
            {{ options.regionId_dictText || options.restaurant.regionName }}
          </view>
        </view>
      </view>

      <view class="wrapper-item" style="margin-top: 15rpx">
        <u-tabs :list="list" lineColor="#00C9AE" lineWidth="40" :current="activeIndex" :inactiveStyle="inactiveStyle"
          :activeStyle="{ color: '#333333' }" @click="tabsClick"></u-tabs>

        <view v-if="activeIndex == 0" class="real-time">
          <view class="realEch" v-if="realechFlag">
            <my-echarts id="main" ref="mapChart" :onInit="initChart" />
          </view>

          <view class="real-tenmin">
            <image :src="
                baseImgUrl +
                (options.monitorStatus ? 'deviceon_3.png' : 'deviceoff_3.png')
              " mode="aspectFill"></image>
            <image :src="
                baseImgUrl +
                (options.purifyStatus ? 'deviceon_1.png' : 'deviceoff_1.png')
              " mode="aspectFill"></image>
            <image :src="
                baseImgUrl +
                (options.fanStatus ? 'deviceon_2.png' : 'deviceoff_2.png')
              " mode="aspectFill"></image>
          </view>

          <view class="ten-averagedata">
            <view>近10分钟平均数据：</view>

            <view class="tenMeter">
              <view class="meterItem">
                <view>油烟浓度</view>
                <view class="value" :class="
                    meanTenList.avgThickSmokeStatus == 2
                      ? 'ypolice'
                      : meanTenList.avgThickSmokeStatus == 3
                      ? 'gpolice'
                      : ''
                  ">
                  {{ meanTenList.avgThickSmoke.toFixed(2) || 0 }}mg/m³
                </view>
              </view>
              <view class="meterItem">
                <view>颗粒物浓度</view>
                <view class="value" :class="
                    meanTenList.avgParticleHazeStatus == 2
                      ? 'ypolice'
                      : meanTenList.avgParticleHazeStatus == 3
                      ? 'gpolice'
                      : ''
                  ">
                  {{ meanTenList.avgParticleHaze.toFixed(2) || 0 }}mg/m³
                </view>
              </view>
              <view class="meterItem">
                <view>非甲烷总烃</view>
                <view class="value" :class="
                    meanTenList.avgNonMethaneStatus == 2
                      ? 'ypolice'
                      : meanTenList.avgNonMethaneStatus == 3
                      ? 'gpolice'
                      : ''
                  ">
                  {{ meanTenList.avgNonMethane.toFixed(2) || 0 }}mg/m³
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="activeIndex == 1" class="real-time">
          <view class="outDay">
            <view>
              <image :src="baseImgUrl + 'qi-icon.png'" mode="aspectFill" class="dayIcon"></image>
              {{ switchingTime }}
            </view>
            <view style="color: #00c9ae" @click="cellTimeClick">
              切换日期
            </view>
          </view>

          <view>
            <view class="realEch" style="margin-top: 20rpx" v-if="realechFlag2">
              <my-echarts id="main" ref="mapChart" :onInit="initChart" />
            </view>
          </view>

          <view class="ten-averagedata">
            <view>当日数据统计：</view>

            <view class="tenMeter">
              <view class="meterItem" style="padding-top: 0">
                <view class="mmol" style="background: #00c9ae">油烟浓度</view>
                <!-- <view class="cautionNum">
                  {{ meanTenList.avgThickSmoke.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（平均值）</view> -->
                <view class="cautionNum">
                  {{ meanTenList.maxThickSmoke.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（最高值）</view>
              </view>

              <view class="meterItem" style="padding-top: 0">
                <view class="mmol" style="background: #f2e064">颗粒物浓度</view>
                <!-- <view class="cautionNum">
                  {{ meanTenList.avgParticleHaze.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（平均值）</view> -->
                <view class="cautionNum">
                  {{ meanTenList.maxParticleHaze.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（最高值）</view>
              </view>

              <view class="meterItem" style="padding-top: 0">
                <view class="mmol" style="background: #6bbbf8">
                  非甲烷总烃浓度
                </view>
                <!-- <view class="cautionNum">
                  {{ meanTenList.avgNonMethane.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（平均值）</view> -->
                <view class="cautionNum">
                  {{ meanTenList.maxNonMethane.toFixed(2) || 0 }}mg/m³
                </view>
                <view class="value valNum">（最高值）</view>
              </view>
            </view>

            <view class="tenMeter">
              <view class="meterItem"
                :data-url="`/deviceManagement/warnRecord/warnRecord?type=1&deviceId=${options.id}&switchingTime=${switchingTime}`"
                @click="handleClickRouter">
                <view class="caution">
                  <image :src="baseImgUrl + 'warning_1.png'" mode="aspectFill"></image>
                </view>
                <view class="title" style="color: #f39835">预警</view>
                <view class="cautionNum">
                  {{ dataCount.earlyWarningCount }}
                </view>
                <view class="value valNum">(次数/次)</view>
                <view class="cautionNum">
                  {{
                    dataCount.earlyWarningTime
                      ? parseInt(dataCount.earlyWarningTime / 60)
                      : 0
                  }}
                </view>
                <view class="value valNum">(持续时间/m)</view>
              </view>

              <view class="meterItem"
                :data-url="`/deviceManagement/warnRecord/warnRecord?type=2&deviceId=${options.id}&switchingTime=${switchingTime}`"
                @click="handleClickRouter">
                <view class="caution">
                  <image :src="baseImgUrl + 'warning_2.png'" mode="aspectFill"></image>
                </view>
                <view class="title" style="color: #f34235">告警</view>
                <view class="cautionNum">
                  {{ dataCount.giveAnAlarmCount }}
                </view>
                <view class="value valNum">(次数/次)</view>
                <view class="cautionNum">
                  {{
                    dataCount.giveAnAlarmTime
                      ? parseInt(dataCount.giveAnAlarmTime / 60)
                      : 0
                  }}
                </view>
                <view class="value valNum">(持续时间/m)</view>
              </view>

              <view class="meterItem"
                :data-url="`/deviceManagement/warnRecord/warnRecord?type=3&deviceId=${options.id}&switchingTime=${switchingTime}`"
                @click="handleClickRouter">
                <view class="caution">
                  <image :src="baseImgUrl + 'warning_3.png'" mode="aspectFill" class="warnThree"></image>
                </view>
                <view class="title" style="color: #a1a1a1">离线</view>
                <view class="cautionNum">
                  {{ dataCount.offLineCount }}
                </view>
                <view class="value valNum">(次数/次)</view>
                <view class="cautionNum">
                  {{
                    dataCount.offLineTime
                      ? parseInt(dataCount.offLineTime / 60)
                      : 0
                  }}
                </view>
                <view class="value valNum">(持续时间/m)</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date" :formatter="formatter"
      :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose()"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
  </view>
</template>

<script>
  import {
    findDeviceData,
    findHeartbeatData,
    eventRecordFindDeviceData,
  } from "@/api/deviceManage.js";
  import {
    deviceDetail
  } from "@/api/home.js";

  import {
    handleClickRouter,
    formatters,
    dayTurnTime
  } from "@/utils/util.js";
  import * as echarts from "@/common/echarts.min.js";
  //import myEcharts from "@/components/mpvue-echarts/src/echarts.vue";
  import myEcharts from "../../components/mpvue-echarts/src/echarts.vue";
  import mixin from "@/utils/mixin.js";

  export default {
    mixins: [mixin],
    components: {
      myEcharts,
    },
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        options: {},
        echarts,
        activeIndex: 0,
        devList: [{
            id: 0,
            name: "监测仪",
            flag: 1,
            devUrl: "/deviceManagement/monitorInfo/monitorInfo",
          }, //0:  未填写   1：已填写
          {
            id: 1,
            name: "净化器",
            flag: 0,
            devUrl: "/deviceManagement/addCleansing/addCleansing",
          },
          {
            id: 2,
            name: "排风机",
            flag: 0,
            devUrl: "/deviceManagement/addCleansing/addwmInfo",
          },
          {
            id: 3,
            name: "烟道",
            flag: 0,
            devUrl: "/deviceManagement/addCleansing/flueInfo",
          },
        ],
        list: [{
            name: "实时数据",
            badge: {
              isDot: false,
            },
          },
          {
            name: "历史数据",
            badge: {
              isDot: false,
            },
          },
        ],
        meanTenList: {}, // 油烟、颗粒物、非甲烷数据
        switchingTime: formatters(new Date(), "YY/MM/DD"), // 历史数据 切换日期
        dataCount: {}, // 历史数据 当日数据统计
        xData: [],
        serDataList: [],
        realechFlag: false,
        realechFlag2: false,
        timerVal: "",
      };
    },
    onLoad(options) {
      this.options = JSON.parse(decodeURIComponent(options.data));
      this.devList[1].flag = this.options.purifyInfoStatus;
      this.devList[2].flag = this.options.fanInfoStatus;
      this.devList[3].flag = this.options.smokeInfoStatus;

      this.getList("first");
      this.getrealTime();
      this.timerVal = setInterval(() => {
        this.getrealTime();
      }, 30000); // 30s
    },
    onShow() {
      uni.$on("deviceInfoData", (data) => {
        deviceDetail({
          deviceId: data
        }).then((res) => {
          this.options = res.result;
          this.devList[1].flag = this.options.purifyInfoStatus;
          this.devList[2].flag = this.options.fanInfoStatus;
          this.devList[3].flag = this.options.smokeInfoStatus;

          this.getList("first");
          this.getrealTime();
          this.timerVal = setInterval(() => {
            this.getrealTime();
          }, 30000);
        });
      });
    },
    onHide() {
      clearInterval(this.timerVal);
    },
    methods: {
      handleClickRouter,
      formatters,
      daySub(v) {
        if (v < 0) {
          let vto = v.toString();
          return `逾期${vto.substring(1)}天`;
        }
        return v + "天";
      },
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick() {
        var minDateNum = +new Date(); //获取当前时间的毫秒数
        this.maxDate = minDateNum;
        this.timeValue = this.maxDate;
        setTimeout(() => {
          this.datetimeShow = true;
          this.realechFlag2 = false;
        }, 100);
      },
      pickerTimeClose() {
        this.datetimeShow = false;
        this.realechFlag2 = true;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          this.switchingTime = formatters(arr, "YY/MM/DD");
          this.getList("second");
          this.warnList();
        }
        this.datetimeShow = false;
        this.realechFlag2 = true;
      },
      initChart(canvas, width, height) {
        let {
          xData,
          serDataList
        } = this.$options.parent;
        console.log("图标", canvas);
        let chart = null;
        chart = echarts.init(canvas, null, {
          width: width,
          height: height,
        });

        var option = {
          tooltip: {
            trigger: "axis",
          },
          legend: {
            data: ["油烟浓度", "颗粒物浓度", "非甲烷总烃"],
          },
          grid: {
            top: "58",
            left: "10%",
            right: "7%",
            bottom: "3%",
            containLabel: true,
          },
          toolbox: {
            feature: {
              saveAsImage: {},
            },
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: xData, // 固定放6个
            axisLabel: {
              rotate: 45,
              margin: 10,
            },
          },
          yAxis: {
            type: "value",
            name: "浓度mg/m³",
            nameTextStyle: {
              color: "#A1A1A1",
            },
          },
          color: ["#2CD5BE", "#F1DC51", "#6BBBF8"], // 三个折线的颜色
          series: [{
              name: "油烟浓度",
              data: serDataList.thickSmoke,
              type: "line",
              stack: "Total",
              showSymbol: false,
              areaStyle: {
                color: "#26DFC6",
              },
              smooth: 0.5, // 设置折线弧度
            },
            {
              name: "颗粒物浓度",
              data: serDataList.particleHaze,
              type: "line",
              stack: "Total",
              showSymbol: false,
              areaStyle: {
                color: "#F1DC51",
              },
              smooth: 0.5, // 设置折线弧度
            },
            {
              name: "非甲烷总烃",
              data: serDataList.nonMethane,
              type: "line",
              stack: "Total",
              showSymbol: false,
              areaStyle: {
                color: "#92CFFE",
              },
              smooth: 0.5, // 设置折线弧度
            },
          ],
        };

        chart.setOption(option);
        return chart; // 返回 chart 后可以自动绑定触摸操作
      },
      tabsClick(item) {
        this.activeIndex = item.index;
        if (this.activeIndex == 0) {
          this.getList("first");
          this.getrealTime();
          this.timerVal = setInterval(() => {
            this.getrealTime();
          }, 30000);
        } else if (this.activeIndex == 1) {
          this.getList("second");
          this.warnList();
          this.getHistory();
          clearInterval(this.timerVal);
        }
      },
      getList(marking) {
        var dataTen = {};
        if (marking == "first") {
          dataTen = {
            monitorMn: this.options.monitorMn || this.options.deviceMonitorMn,
            startDate: +new Date() - 10 * 60 * 1000,
            endDate: +new Date(),
          };
        } else {
          dataTen = {
            monitorMn: this.options.monitorMn || this.options.deviceMonitorMn,
            startDate: dayTurnTime(this.switchingTime + " 00:00:00"),
            endDate: dayTurnTime(this.switchingTime + " 23:59:59"),
          };
        }

        findDeviceData(dataTen).then((res) => {
          this.meanTenList = res.result[0];
        });
      },
      // 实时数据
      getrealTime() {
        this.xData = [];
        let day = formatters(new Date(), "YY/MM/DD");
        let dataLine = {
          monitorMn: this.options.monitorMn || this.options.deviceMonitorMn,
          startDate: dayTurnTime(day + " 00:00:00"),
          endDate: +new Date(),
        };
        findHeartbeatData(dataLine).then((res) => {
          let {
            heartbeatTime,
            thickSmoke,
            particleHaze,
            nonMethane
          } =
          res.result;
          let timeList = heartbeatTime.splice(-12, 12);
          for (var v of timeList) {
            // this.xData.push(`${v.substring(11)}\n${v.substring(5, 10)}`);   不要删
            this.xData.push(`${v.substring(11)}`);
          }
          this.serDataList.thickSmoke = thickSmoke.splice(-12, 12);
          this.serDataList.particleHaze = particleHaze.splice(-12, 12);
          this.serDataList.nonMethane = nonMethane.splice(-12, 12);
          this.realechFlag = false;
          setTimeout(() => {
            this.realechFlag = true;
          }, 500);
          this.realechFlag2 = false;
        });
      },
      warnList() {
        let data = {
          deviceId: this.options.id,
          startDate: dayTurnTime(this.switchingTime + " 00:00:00"),
          endDate: dayTurnTime(this.switchingTime + " 23:59:59"),
        };
        eventRecordFindDeviceData(data).then((res) => {
          this.dataCount = res.result;
        });
      },
      // 历史数据
      getHistory() {
        this.xData = [];
        let day = formatters(new Date(), "YY/MM/DD");
        let dataLine = {
          monitorMn: this.options.monitorMn || this.options.deviceMonitorMn,
          startDate: dayTurnTime(day + " 00:00:00"),
          endDate: dayTurnTime(day + " 23:59:59"),
        };
        findHeartbeatData(dataLine).then((res) => {
          let {
            heartbeatTime,
            thickSmoke,
            particleHaze,
            nonMethane
          } =
          res.result;

          for (var v of heartbeatTime) {
            this.xData.push(`${v.substring(11)}`);
          }
          this.serDataList.thickSmoke = thickSmoke;
          this.serDataList.particleHaze = particleHaze;
          this.serDataList.nonMethane = nonMethane;
          this.realechFlag = false;
          this.realechFlag2 = true;
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .deviceManInfo {
    height: 100%;

    .wrapper-content {
      background: #f9f9f9;
      height: 100%;
      padding: 24rpx 20rpx;

      .wrapper-item {
        padding: 20rpx 25rpx;
        background-color: #ffffff;
      }
    }

    .device-name {
      font-size: 30rpx;
      color: #030303;
      font-weight: bold;
    }

    .mnCode {
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #a1a1a1;
      font-weight: 400;
    }

    .item-content {
      display: flex;
      flex-wrap: wrap;
      margin-top: 20rpx;
      font-size: 24rpx;

      .item-cycle {
        position: relative;
        text-align: center;
        width: 25%;

        .devicename {
          padding: 10rpx 0;
          width: 90%;
          border: 1px solid #e8e8e8;
          border-radius: 32rpx;
          color: #666666;
          font-size: 26rpx;

          image {
            margin-right: 8rpx;
            vertical-align: text-bottom;
            width: 30rpx;
            height: 30rpx;
          }
        }
      }

      .con-cycle {
        padding-top: 20rpx;
        position: relative;
        text-align: center;
        width: 33%;

        .cycleName {
          color: #a1a1a1;
        }

        .cycleTime {
          margin: 10rpx 0 20rpx;
          color: #333333;
          font-weight: bold;
        }
      }
    }

    .dining-room {
      margin-top: 20rpx;
      font-size: 30rpx;
      color: #333333;
      font-weight: bold;

      .din-title {
        display: flex;

        image {
          margin-right: 10rpx;
          margin-top: 9rpx;
          width: 30rpx;
          height: 28rpx;
        }
      }

      .dinAddress {
        font-size: 28rpx;
        font-weight: 400;
        color: #333333;

        text {
          color: #a1a1a1;
        }
      }
    }

    .real-time {
      margin-top: 20rpx;
      width: 100%;

      .realEch {
        overflow-x: auto;
        height: 400rpx;

        /deep/canvas {
          z-index: 999;
        }
      }

      .real-tenmin {
        margin-top: 10rpx;

        image {
          width: 180rpx;
          height: 48rpx;
        }

        image:nth-of-type(2) {
          margin: 0 10rpx;
        }
      }

      .ten-averagedata {
        margin-top: 10rpx;
        font-size: 28rpx;
        color: #333333;
        font-weight: bold;

        .tenMeter {
          display: flex;
          justify-content: space-between;
          margin-top: 10rpx;
          font-size: 24rpx;
          color: #666666;
          font-weight: 400;

          .meterItem {
            padding: 15rpx 0 13rpx;
            text-align: center;
            font-size: 24rpx;
            width: 200rpx;
            line-height: 45rpx;
            background: #f5f7f9;
            border-radius: 8rpx;

            .value {
              color: #333333;
              font-size: 26rpx;
              font-weight: bold;
            }

            // 预警
            .ypolice {
              color: #f39835 !important;
            }

            // 告警
            .gpolice {
              color: #f34235 !important;
            }

            .valNum {
              color: #bbbbbb;
              font-weight: 400;
            }

            .caution {
              image {
                width: 48rpx;
                height: 42rpx;
              }

              .warnThree {
                width: 42rpx;
                height: 42rpx;
              }
            }

            .title {
              font-size: 28rpx;
              font-weight: 500;
            }

            .mmol {
              margin-bottom: 10rpx;
              padding: 15rpx 0;
              font-size: 26rpx;
              color: #ffffff;
              font-weight: bold;
              border-top-right-radius: 8rpx;
              border-top-left-radius: 8rpx;
            }

            .cautionNum {
              font-size: 30rpx;
              color: #333333;
              font-weight: bold;
            }
          }
        }
      }

      .outDay {
        display: flex;
        justify-content: space-between;
        padding: 22rpx 25rpx;
        border-radius: 40rpx;
        background: #f9f9f9;

        color: #333333;
        font-size: 26rpx;

        .dayIcon {
          margin-right: 10rpx;
          width: 26rpx;
          height: 26rpx;
        }
      }
    }
  }

  /deep/.u-picker__view {
    height: 600rpx !important;
  }
</style>